import React from 'react';
import { Modal, Form, Input, DatePicker, Select, Button, message } from 'antd';
import moment, { Moment } from 'moment';

const { Option } = Select;

interface UpdateFormProps {
  updateModalVisible: boolean;
  onCancel: () => void;
  onSubmit: (values: any) => void;
  values: any;
}

const UpdateForm: React.FC<UpdateFormProps> = ({ updateModalVisible, onCancel, onSubmit, values }) => {
  const [form] = Form.useForm();

  // 初始化表单数据
  React.useEffect(() => {
    form.setFieldsValue({
      ...values,
      create_time: values.create_time ? moment(values.create_time) : null,
    });
  }, [values, form]);

  const handleSubmit = async () => {
    try {
      const updatedValues = await form.validateFields();
      const formattedValues = {
        ...updatedValues,
        create_time: updatedValues.create_time?.format('YYYY-MM-DD HH:mm:ss'),
      };
      onSubmit(formattedValues);
      form.resetFields();
    } catch (error) {
      message.error('请检查表单字段是否正确填写');
    }
  };

  return (
    <Modal
      title="编辑"
      visible={updateModalVisible}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          提交
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical">
        {/* Username */}
        <Form.Item
          label="Username"
          name="username"
          rules={[
            { required: true, message: '用户名不可为空' },
          ]}
        >
          <Input placeholder="请输入用户名" disabled />
        </Form.Item>

        {/* Display Name */}
        <Form.Item
          label="Display Name"
          name="display_name"
          rules={[
            { required: false },
          ]}
        >
          <Input placeholder="请输入显示名称（可选）" />
        </Form.Item>

        {/* Create Time */}
        <Form.Item
          label="Create Time"
          name="create_time"
          rules={[
            {
              required: true,
              message: '创建时间不可为空'
            },
            ({ getFieldValue }) => ({
              validator(_, value: Moment | null) {
                if (!value || !value.isValid()) {
                  return Promise.reject('请选择有效的创建时间');
                }
                return Promise.resolve();
              },
            }),
          ]}
        >
          <DatePicker placeholder="请选择创建时间" showTime />
        </Form.Item>

        {/* Status */}
        <Form.Item
          label="Status"
          name="status"
          rules={[
            { required: true, message: '状态不可为空' },
          ]}
        >
          <Select placeholder="请选择状态">
            <Option value={1}>Enabled</Option>
            <Option value={0}>Disabled</Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UpdateForm;